﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
using Vit.Web.Models;

namespace Vit.CMS.Data
{
    public class DataSources
    {
        private static List<string> sites;
        public static List<string> Sites
        {
            get
            {
                if (sites == null)
                {
                    sites = new List<string>();
                    DirectoryInfo dir = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Sites"));
                    foreach (DirectoryInfo sd in dir.GetDirectories())
                    {
                        sites.Add(sd.Name);
                    }
                }
                return sites;
            }
        }

        public static string GetJsonLayouts()
        {
            WebSite site = ((Vit.Web.VitApplication)HttpContext.Current.ApplicationInstance).CurrentSite;
            return GetJsonLayouts(site.Name);
        }

        public static string GetJsonLayouts(string siteName)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();
            return ser.Serialize(GetLayouts(siteName));
        }

        public static List<LayoutInfo> GetLayouts()
        {
            WebSite site = ((Vit.Web.VitApplication)HttpContext.Current.ApplicationInstance).CurrentSite;
            return GetLayouts(site.Name);
        }

        public static List<LayoutInfo> GetLayouts(string siteName)
        {
            List<LayoutInfo> layouts = new List<LayoutInfo>();
            DirectoryInfo dir = new DirectoryInfo(HttpContext.Current.Server.MapPath(string.Format("~/Sites/{0}/Themes/", siteName)));
            foreach (DirectoryInfo sd in dir.GetDirectories())
            {
                LayoutInfo li = new LayoutInfo();
                li.LayoutName = sd.Name;

                DirectoryInfo[] skinDirs = sd.GetDirectories("Skins", SearchOption.TopDirectoryOnly);
                if (skinDirs != null && skinDirs.Length > 0)
                {
                    foreach (FileInfo sf in skinDirs[0].GetFiles("*.ascx"))
                    {
                        li.Skins.Add(sf.Name.Replace(sf.Extension, ""));
                    }
                }

                foreach (FileInfo ptf in sd.GetFiles("*.ascx"))
                {
                    li.PageTemplates.Add(ptf.Name.Replace(ptf.Extension, ""));
                }

                layouts.Add(li);
            }
            return layouts;
        }
    }
}
